/*
 * GoodsFragment.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.main.home;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.base.SuperBaseEventFragment;
import com.yidiandao.business.constant.Intents;
import com.yidiandao.business.constant.Times;
import com.yidiandao.business.data.event.RefreshSecondKillEvent;
import com.yidiandao.business.data.event.SignEvent;
import com.yidiandao.business.data.response.QueryFrameResponse;
import com.yidiandao.business.data.response.QueryHomeHeaderResponse;
import com.yidiandao.business.ui.adapter.HomeAdapter;
import com.yidiandao.business.ui.main.MainActivity;
import com.yidiandao.business.ui.orderabout.order.OrderActivity;
import com.yidiandao.business.ui.searchabout.searchshopandgoods.SearchActivity;
import com.yidiandao.business.ui.url.UrlActivity;
import com.yidiandao.business.ui.widget.dialog.BusinessDialog;
import com.yidiandao.business.ui.widget.dialog.FrameDialog;
import com.yidiandao.business.ui.widget.listview.DisplayListItem;
import com.yidiandao.business.ui.widget.view.AbsListViewScrollDetector;
import com.yidiandao.business.ui.widget.view.BannerView;
import com.yidiandao.business.ui.widget.view.PtrClassicAutoFrameLayout;
import com.yidiandao.business.ui.widget.view.RatioLayout;
import com.yidiandao.business.utils.AnimatorUtils;
import com.yidiandao.business.utils.JumpUtils;
import com.yidiandao.business.utils.PreferenceUtils;
import com.yidiandao.business.utils.SysUtils;
import com.yidiandao.business.utils.UIUtils;
import com.yidiandao.business.utils.UmengUtils;
import com.yidiandao.business.utils.UrlUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * 首页-商品-View
 */
public class HomeFragment extends SuperBaseEventFragment
        implements HomeContract.View, View.OnClickListener {

    public static final String TAG = HomeFragment.class.getSimpleName();

    private HomeContract.Presenter mPresenter;

    private HomeAdapter mHomeAdapter;

    private BannerView mBannerView;

    private ListView mListView;

    private PtrClassicAutoFrameLayout mPtrFrame;

    private View mHeaderView;

    private ImageView mIvToTop;

    private TextView mIbtnSearch;

    private View mViewLine;

    private LinearLayout mLlToolbarHeader;

    private TextView mIbtnSearchHeader;

    private RatioLayout mBannerLayout;

    private FrameDialog mFrameDialog;

    private LinearLayout mLlToolbar;

    private ImageView mIvSignTip;

    private ImageView mIvSignTipHalfHidden;

//    private ImageView mIvRefreshImage;

//    private RatioLayout mRatioRefreshImage;

    private boolean isVisibility;

    private boolean isOpening, isHiding;

    private int mScrollHeight;

    // 是否展示签到提示
    private boolean mSignTipVisible;

    // 签到提示处于半隐藏
    private boolean isHalfHidden = false;

    private int mNotReceiveOrderCount;

    private long mPreTime;

    // 是否弹出提示收货信息
    private boolean isShowUnGetGoodsTipDialog;

    private boolean isFirstLoad = true;

    AbsListViewScrollDetector mScrollDetector = new AbsListViewScrollDetector() {
        @Override
        public void onScrollUp() {
            changeToolBarAndSignTipStatus();
            // 动画隐藏
            hideAnimator(mIvToTop);
        }

        @Override
        public void onScrollDown() {
            changeToolBarAndSignTipStatus();
            if (UIUtils.getListViewScrollY(mListView)
                    > SysUtils.getScreenHeight(UIUtils.getContext())) {
                // 动画显示
                showAnimator(mIvToTop);
            } else {
                // 动画隐藏
                hideAnimator(mIvToTop);
            }
        }
    };

    public static HomeFragment getInstance() {
        return new HomeFragment();
    }

    @Override
    public void setPresenter(HomeContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public String getPagerTag() {
        return TAG;
    }

    @Override
    protected void initViews() {
        mPtrFrame = (PtrClassicAutoFrameLayout) mRootView.findViewById(R.id.ptr_frame);
        mListView = (ListView) mRootView.findViewById(R.id.list_view);
        mIvToTop = (ImageView) mRootView.findViewById(R.id.iv_to_top);
        mIbtnSearch = (TextView) mRootView.findViewById(R.id.ibtn_search);
//        mRatioRefreshImage = (RatioLayout) mRootView.findViewById(R.id.ratio_refresh_image);
//        mIvRefreshImage = (ImageView) mRootView.findViewById(R.id.iv_refresh_image);

        mViewLine = mRootView.findViewById(R.id.view_line);
        mLlToolbar = (LinearLayout) mRootView.findViewById(R.id.ll_toolbar);
        // Banner图
        mHeaderView = LayoutInflater.from(mActivity).inflate(R.layout.item_home_banner, mListView, false);
        mBannerView = (BannerView) mHeaderView.findViewById(R.id.banner_view);
        mBannerLayout = (RatioLayout) mHeaderView.findViewById(R.id.banner_layout);

        mLlToolbarHeader = (LinearLayout) mHeaderView.findViewById(R.id.ll_toolbar_header);
        mIbtnSearchHeader = (TextView) mHeaderView.findViewById(R.id.ibtn_search_header);

        //签到提示
        mIvSignTip = (ImageView) mRootView.findViewById(R.id.iv_sign_tip);
        mIvSignTipHalfHidden = (ImageView) mRootView.findViewById(R.id.iv_sign_tip_halfHidden);

        initListView();
        initUlPtr();
        initSignTip();
        initExtra();
        initListeners();
    }

    private void initExtra() {
        mScrollHeight = (int) (SysUtils.getScreenWidth(mActivity) / mBannerLayout.getRatio());
        mScrollDetector.setListView(mListView);
        mListView.setOnScrollListener(mScrollDetector);
        mIvToTop.setAlpha(0.0f);

        updateToolBarAlpha();
        postAutoHideSignHintTask();
    }

    private void initListView() {
        mListView.addHeaderView(mHeaderView);
        mHomeAdapter = new HomeAdapter(mActivity);
        mListView.setAdapter(mHomeAdapter);
    }

    private void initUlPtr() {
        mPtrFrame.disableWhenHorizontalMove(true);
        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mPresenter.loadHomeData();
            }
        });

//        mPtrFrame.setOnUIPositionChangeListener(new PtrClassicAutoHeader.OnUIPositionChangeListener() {
//            @Override
//            public void onUIPositionChanged(int positionY) {
//                // todo 设置图片的margin
//                LogUtils.d("positionY --> " + positionY);
//
//                int height = mRatioRefreshImage.getHeight();
//                if (height > 0) {
//                    mRatioRefreshImage.setVisibility(View.VISIBLE);
//                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mRatioRefreshImage.getLayoutParams();
//                    params.topMargin = -height + positionY;
//                    mRatioRefreshImage.setLayoutParams(params);
//                }
//
//            }
//        });
    }

    private void initListeners() {
        mIvToTop.setOnClickListener(this);
        mIbtnSearchHeader.setOnClickListener(this);
        mIbtnSearch.setOnClickListener(this);
        mIvSignTip.setOnClickListener(this);
        mIvSignTipHalfHidden.setOnClickListener(this);

        mBannerView.setOnSingleClickListener(new BannerView.OnSingleClickListener() {
            @Override
            public void onClick(int position) {
                UmengUtils.onEvent(mActivity, R.string.umeng_home_click_banner);
                List<QueryHomeHeaderResponse.Banner> banners = mPresenter.getBannerList();
                QueryHomeHeaderResponse.Banner banner = banners.get(position);
                JumpUtils.clickBanner(mActivity, banner);
            }
        });
    }

    private void changeToolBarAndSignTipStatus() {
        updateToolBarAlpha();
        isHalfHidden = true;
        if (mSignTipVisible) {
            mIvSignTip.setVisibility(View.GONE);
            mIvSignTipHalfHidden.setVisibility(View.VISIBLE);
            postAutoHideSignHintTask();
        } else {
            mIvSignTip.setVisibility(View.GONE);
            mIvSignTipHalfHidden.setVisibility(View.GONE);
        }
    }

    private void updateToolBarAlpha() {
        if (mScrollHeight != 0) {
            int alpha;
            int verticalOffset = UIUtils.getListViewScrollY(mListView);

            if (verticalOffset != 0) {
                alpha = verticalOffset * 255 / mScrollHeight;
                if (alpha > 255)
                    alpha = 255;
            } else {
                alpha = 0;
            }
            //toolbar实际是两个  当滑动渐变时另一个不可见
            mLlToolbarHeader.setVisibility(alpha <= 5 ? View.VISIBLE : View.GONE);
            mLlToolbar.setVisibility(alpha <= 5 ? View.GONE : View.VISIBLE);

            mViewLine.setBackgroundColor(Color.argb(alpha, 235, 235, 235));
            mLlToolbar.setBackgroundColor(Color.argb(alpha, 255, 255, 255));
            if (alpha <= 200) {
                mIbtnSearch.setTextColor(UIUtils.getColor(R.color.white));
                UIUtils.setTextDrawableLeft(mIbtnSearch, R.mipmap.ic_home_search_white);
                mIbtnSearch.setBackgroundResource(R.drawable.bg_home_search_black);
            } else {
                mIbtnSearch.setTextColor(UIUtils.getColor(R.color.home_toolbar_text));
                UIUtils.setTextDrawableLeft(mIbtnSearch, R.mipmap.ic_home_search);
                mIbtnSearch.setBackgroundResource(R.drawable.bg_home_search_gray);
            }
        }
    }

    /**
     * 显示动画
     */
    private void showAnimator(View view) {
        AnimatorUtils.showToTopAnimator(view, isVisibility, isOpening, new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                isOpening = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isVisibility = true;
                isOpening = false;
            }
        });
    }

    /**
     * 隐藏动画
     */
    private void hideAnimator(final View view) {
        AnimatorUtils.hideToTopAnimator(view, isVisibility, isHiding, new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                isHiding = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.GONE);
                isVisibility = false;
                isHiding = false;
            }
        });
    }

    @Override
    protected void startLoadData() {
        mPresenter.start();
    }

    @Override
    public void refreshContent(int result) {
        superRefreshLayoutState(result);
    }

    @Override
    public int checkResultObject(Object resultObject) {
        return superCheckListState(resultObject);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void showToast(String text) {
        UIUtils.showToast(text);
    }

    @Override
    public void setBannerData(List<String> banners) {
        if (banners != null && banners.size() == 0) {
            if (mBannerLayout != null && mBannerLayout.getVisibility() == View.VISIBLE) {
                mBannerLayout.setVisibility(View.GONE);
            }
        } else {
            if (mBannerLayout != null && mBannerLayout.getVisibility() == View.GONE) {
                mBannerLayout.setVisibility(View.VISIBLE);
            }
            if (mBannerView != null) {
                mBannerView.setData(banners);
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mBannerView != null) {
            mBannerView.startPlay();
        }
        mPresenter.onFragmentStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mBannerView != null) {
            mBannerView.stopPlay();
        }
        mPresenter.onFragmentStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        // 避免内存泄漏
        mBannerView = null;
    }

    @Override
    public List<DisplayListItem> getDisplayListItems() {
        return mHomeAdapter.getData();
    }

    @Override
    public void setDisplayListItems(List<DisplayListItem> displayListItems) {
        if (null != mHomeAdapter)
            mHomeAdapter.setData(displayListItems);
    }

    @Override
    public void notifyDataChanged() {
        mListView.setSelection(0);
        mPresenter.start();
        mPresenter.reCheckSign();
    }

    @Override
    public void smoothToTop() {
        if (mListView != null) {
            mListView.post(new Runnable() {
                @Override
                public void run() {
                    mListView.requestFocus();
                    mListView.smoothScrollToPosition(0);
                }
            });
        }
    }

    @Override
    public void toSearchActivity() {
        SearchActivity.actionStart(mActivity, 0);
    }

    @Override
    public void showFrameDialog(Bitmap bitmap, QueryFrameResponse.Frame frame) {

        if (!isHomeTabOfMainActivity()) {
            return;
        }

        mFrameDialog = new FrameDialog(mActivity);
        mFrameDialog.show();
        mFrameDialog.setFrameImageRatio(frame.getRatio());
        mFrameDialog.setFrameData(frame);
        mFrameDialog.setFrameImage(bitmap);

        mPresenter.startTimer();

        mFrameDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                showUnGetGoodsTipDialog(mNotReceiveOrderCount);
            }
        });
    }

    public boolean isHomeTabOfMainActivity() {
        return HomeFragment.TAG.equals(((MainActivity) mActivity).getCurrentTag());
    }

    @Override
    public void autoHideFrameDialog() {
        if (mFrameDialog != null && mFrameDialog.isShowing()) {
            mFrameDialog.dismiss();
        }
    }

    @Override
    public void setToolbarVisible() {
        mLlToolbar.setVisibility(View.VISIBLE);
    }

    @Override
    public void notifyDataSetChanged() {
        mHomeAdapter.notifyDataSetChanged();
    }

    @Override
    public void setRefreshComplete() {
        if (mPtrFrame != null) {
            mPtrFrame.refreshComplete();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            mPresenter.onFragmentCreate();
        }
    }


    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.iv_to_top:
                // 返回顶部
                smoothToTop();
                break;
            case R.id.ibtn_search:
            case R.id.ibtn_search_header:
                toSearchActivity();
                break;
            case R.id.iv_sign_tip:
                //                if (!PreferenceUtils.getToken(UIUtils.getContext())
                //                        .equals(PreferenceUtils.STRING_DEFAULT)) {
                String string = PreferenceUtils.getString(UIUtils.getContext(), Intents.SIGN_URL, PreferenceUtils.STRING_DEFAULT, false);
                String url = UrlUtils.jointUrl(string);
                UrlActivity.actionStartWithoutShareFeature(mActivity, url);
                //                SignActivity.actionStart(mActivity);
                //                } else {
                //                    LoginActivity.actionStart(mActivity);
                //                }
                break;
            case R.id.iv_sign_tip_halfHidden:
                mIvSignTip.setVisibility(View.VISIBLE);
                mIvSignTipHalfHidden.setVisibility(View.GONE);
                isHalfHidden = false;
                postAutoHideSignHintTask();
                break;
        }
    }

    private void postAutoHideSignHintTask() {
        if (mIvSignTip.getVisibility() == View.VISIBLE) {
            UIUtils.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isHalfHidden = true;
                    mIvSignTip.setVisibility(View.GONE);
                    mIvSignTipHalfHidden.setVisibility(View.VISIBLE);
                }
            }, 3000);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    @Override
    public void onEventMainThread(RefreshSecondKillEvent event) {
        mPresenter.getNewSecondKillData();
    }

    private void initSignTip() {
        mPresenter.reCheckSign();
    }

    @Override
    public void setSignTipVisible(boolean visible) {
        mSignTipVisible = visible;
        if (null != mIvSignTip) {
            if (isHalfHidden) {
                mIvSignTipHalfHidden.setVisibility(visible ? View.VISIBLE : View.GONE);
            } else {
                mIvSignTip.setVisibility(visible ? View.VISIBLE : View.GONE);
                postAutoHideSignHintTask();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstLoad) {
            return;
        }
        if (isShowUnGetGoodsTipDialog) {
            long currentTimeMillis = System.currentTimeMillis();
            if ((currentTimeMillis - mPreTime) / Times.ONE_MINUTE_IN_MILLIS >= 1) {
                mPresenter.getUnGetGoodsFromNet(true);
            }
        }
    }

    @Override
    public void showUnGetGoodsTipDialog(int num) {
        isFirstLoad = false;
        if (num == 0) {
            return;
        }
        isShowUnGetGoodsTipDialog = true;
        mPreTime = System.currentTimeMillis();
        String count = num > 99 ? "99+" : num + "";
        new BusinessDialog.Builder(mActivity)
                .setCancelable(false)
                .setTitle(UIUtils.getString(R.string.dialog_get_goods_title, count))
                .setMessage(UIUtils.getString(R.string.dialog_get_goods_content))
                .setPositiveButton(UIUtils.getString(R.string.dialog_check_order),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                OrderActivity.actionStart(mActivity, 3);
                            }
                        })
                .setNegativeButton(UIUtils.getString(R.string.dialog_close_tip), null)
                .create()
                .show();
    }

    @Override
    public void setUnGetGoodsCount(int count) {
        mNotReceiveOrderCount = count;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetTipVisiable(SignEvent event) {
        if (event.mChangeToggle) {
            mPresenter.reCheckSign();
        } else {
            mSignTipVisible = false;
            mIvSignTip.setVisibility(View.GONE);
            mIvSignTipHalfHidden.setVisibility(View.GONE);
        }
    }
}
